package we.dispatcher;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import we.common.CCommonHandle;
import we.common.CDebug;
import we.config.CConstant;
import we.session.CAttachment;

public class CWriteHandle implements Runnable
{

    BlockingQueue<CMessage> out;
    ByteBuffer policyData;
    Charset charset;
    CharsetEncoder encoder;

    public CWriteHandle(BlockingQueue<CMessage> out)
    {
        this.out = out;

        charset = Charset.forName(CConstant.DEFAULT_ENCODING);
        encoder = charset.newEncoder();
        initPolicyData();
    }

    public void run()
    {
        while (true)
        {
            try
            {
                CMessage msg = out.take();
                //  CDebug.Trace(this, "write ready...");
                ByteBuffer bb = msg.data;
                if (bb != null)
                {
                    CCoreServer.instance().getHandler().MessageSent(((CAttachment) msg.key.attachment()).session, msg);
                    if (msg.key.isValid())
                    {
//                        while (bb.hasRemaining())
//                        {
                            ((SocketChannel) msg.key.channel()).write(bb);                            
//                        }
                    } 
                     
                } else
                {
                    CCoreServer.instance().SendMsg(msg.key, policyData.duplicate());
                }
                msg.dispose();
            } catch (Exception e)
            {
                CDebug.Trace(this, "--------------Ket thuc writing");
                CCommonHandle.writeErrLog(e);
            }
        }
    }

    private void initPolicyData()
    {
        try
        {
            String response = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>";
            CharBuffer tempChar = CharBuffer.wrap(response.toString().toCharArray());
            policyData = encoder.encode(tempChar);
        } catch (CharacterCodingException ex)
        {
            Logger.getLogger(CWriteHandle.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
